<?php

class base_task {

    function install_options() {
        return array(
            'db_host' => array(
                'type' => 'text',
                'vtype' => 'required',
                'required' => true,
                'title' => app::get('base')->_('数据库主机'),
                'default' => '127.0.0.1'
            ),
            'db_user' => array(
                'type' => 'text',
                'vtype' => 'required',
                'required' => true,
                'title' => app::get('base')->_('数据库用户名'),
                'default' => 'root'
            ),
            'db_password' => array(
                'type' => 'password',
                'title' => app::get('base')->_('数据库密码'),
                'default' => ''
            ),
            'db_name' => array(
                'type' => 'select',
                'vtype' => 'required',
                'required' => true,
                'title' => app::get('base')->_('数据库名'),
                'options_callback' => array(
                    'app' => 'base',
                    'method' => 'dbnames'
                ),
                'onfocus' => 'setuptools.getdata(\'base\', \'dbnames\', this);'
            ),
            'db_prefix' => array(
                'type' => 'text',
                'title' => app::get('base')->_('数据库表前缀'),
                'default' => 'sdb_'
            ),
            'default_timezone' => array(
                'type' => 'select',
                'options' => base_location::timezone_list(),
                'title' => app::get('base')->_('默认时区'),
                'default' => '8',
                'vtype' => 'required',
                'required' => true
            )
        );
    }

    function dbnames($options) {
        $options = $options['base'];
        $link = @mysqli_connect($options['db_host'], $options['db_user'], $options['db_password']);
        if (! $link) {
            return array();
        } else {
            $db_list = mysqli_query($link, 'SHOW databases');
            $i = 0;
            $cnt = mysqli_num_rows($db_list);
            $rows = array();
            while ($i < $cnt) {
                $i++;
                $row = $db_list->fetch_object();
                $dbname = $row->Database;
                $rows[$dbname] = $dbname;
            }
            return $rows;
        }
    }

    // End Function
    function checkenv($options) {
        if (! $options['db_host']) {
            echo app::get('base')->_("Error: 需要填写数据库主机") . "\n";
            return false;
        }
        if (! $options['db_user']) {
            echo app::get('base')->_("Error: 需要填写数据库用户名") . "\n";
            return false;
        }
        if (! $options['db_name']) {
            echo app::get('base')->_("Error: 请选择数据库") . "\n";
            return false;
        }
        if ($options['db_prefix'] && $options['db_prefix'] != 'sdb_' && strpos($options['db_prefix'], 'sdb_') === 0) {
            echo app::get('base')->_("Error: 数据库前缀不支持以'sdb_'开头的两级划分，可改用例如") . "'tbl_" . substr($options['db_prefix'], 4) . "'" . app::get('base')->_("为数据库前缀") . "\n";
            return false;
        }
        
        $link = @mysqli_connect($options['db_host'], $options['db_user'], $options['db_password']);
        if (! $link) {
            echo app::get('base')->_("Error: 数据库连接错误") . "\n";
            return false;
        }
        
        $mysql_ver = mysqli_get_server_info($link);
        if (! version_compare($mysql_ver, '4.1', '>=')) {
            echo app::get('base')->_("Error: 数据库需高于4.1的版本") . "\n";
            return false;
        }
        
        if (! mysqli_select_db($link, $options['db_name'])) {
            echo app::get('base')->_("Error: 数据库") . "\"" . $options['db_name'] . "\"" . app::get('base')->_("不存在") . "\n";
            return false;
        }
        
        if (ECAE_MODE) {
            if (! file_exists(ROOT_DIR . '/config/config.php')) {
                echo app::get('base')->_("Error: 没有找到config文件，ECAE环境下请将base/example下的ecae.config.php改名为config.php放入config文件夹") . "\n";
                return false;
            }
        } else {
            if (! kernel::single('base_setup_config')->write($options)) {
                echo app::get('base')->_("Error: Config文件写入错误") . "\n";
                return false;
            }
        } // todo
        
        if (file_exists(ROOT_DIR . '/config/config.php')) {
            require (ROOT_DIR . '/config/config.php');
        }
        
        date_default_timezone_set(defined('DEFAULT_TIMEZONE') ? ('Etc/GMT' . (DEFAULT_TIMEZONE >= 0 ? (DEFAULT_TIMEZONE * - 1) : '+' . (DEFAULT_TIMEZONE * - 1))) : 'UTC');
        
        return true;
    }

    function pre_install($options) {
        kernel::set_online(false);
        if (ECAE_MODE) {
            if (! file_exists(ROOT_DIR . '/config/config.php')) {
                echo app::get('base')->_("Error: 没有找到config文件，ECAE环境下请将base/example下的ecae.config.php改名为config.php放入config文件夹") . "\n";
                return false;
            }
        } else {
            if (! kernel::single('base_setup_config')->write($options)) {
                echo app::get('base')->_("Error: Config文件写入错误") . "\n";
                return false;
            }
        } // todo
        
        if (file_exists(ROOT_DIR . '/config/config.php')) {
            require (ROOT_DIR . '/config/config.php');
        }
        
        // base_certificate::active();
    }

    function post_install() {
        kernel::single('base_application_manage')->sync();
        kernel::set_online(true);
    }

    function post_update($dbinfo) {
        $dbver = $dbinfo['dbver'];
        if (empty($dbver) || $dbver == '0.1') {
            app::get('base')->model('cache_expires')->delete(array());
            $rows = app::get('base')->model('apps')->getList('app_id', array(
                'installed' => 1
            ));
            $content_detectors['list'] = array(
                'base_application_cache_expires'
            );
            $service = new service($content_detectors);
            foreach ($rows as $row) {
                foreach ($service as $detector) {
                    foreach ($detector->detect(app::get($row['app_id'])) as $name => $item) {
                        $item->install();
                    }
                }
            }
            cachemgr::clean($msg); // 清空缓存
            logger::info('cache expiers update');
        } // 变更cache_expires结构及数据，0.1版本前存在的问题包括0.1
        
        if ($dbver && $dbver == '0.12') {
            // 升级版本，清理原来rpcpoll表里面的大量冗余数据。
            app::get('base')->model('rpcpoll')->delete(array(
                'type' => 'response'
            ));
        }
        
        if ($dbver && $dbver < '0.21') {
            $sql = "insert into sdb_base_setting (select SUBSTRING(prefix,9) as app, `key`, value from sdb_base_kvstore where prefix like 'setting/%' );";
            echo 'init sdb_base_setting data...' . PHP_EOL;
            kernel::database()->exec($sql);
        }
    } // End Function
}
